package com.liuwa.framework.web.service;

import com.liuwa.common.config.SysConfig;
import com.liuwa.framework.config.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @Description:
 * @Author: Liuwa
 * @Date: 2023/1/16 10:02
 */
@Service
public class FileService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 清理临时文件
     */
    public void clearTemp(){

        long expireTime = 1 * 60 * 60 * 1000; // 过期时长

        // 上传文件路径
        String tempPath = SysConfig.getTempPath();
        File dir = new File(tempPath);
        if(!dir.exists()){
            return ;
        }
        long timestamp = System.currentTimeMillis();
        int ignoreFileCount = 0;
        for(File yearDir : dir.listFiles()){
            for(File monthDir : yearDir.listFiles()){
                for(File dateDir : monthDir.listFiles()){
                    for(File file : dateDir.listFiles()){
                        if(timestamp - file.lastModified() < expireTime){
                            ignoreFileCount ++;
                            continue;
                        }
                        file.delete();
                    }
                }
            }
        }

        if(ignoreFileCount == 0){
            clearEmptyDir(dir);
        }

    }





    /**
     * 清理临时下载文件
     */
    public void clearDownload(){
        long expireTime = 30 * 60 * 1000; // 过期时长

        // 上传文件路径
        String downloadPath = SysConfig.getDownloadPath();
        File dir = new File(downloadPath);
        if(!dir.exists()){
            return ;
        }
        long timestamp = System.currentTimeMillis();
        int ignoreFileCount = 0;
        for(File file : dir.listFiles()){
            if(timestamp - file.lastModified() < expireTime){
                ignoreFileCount ++;
                continue;
            }
            file.delete();
        }

        if(ignoreFileCount == 0){
            clearEmptyDir(dir);
        }
    }

    /**
     * 清理空文件夹
     * @param dir
     */
    private void clearEmptyDir(File dir){
        if(dir == null || !dir.exists()){
            return ;
        }
        if(dir.isFile()){
            return ;
        }
        for(File subDir : dir.listFiles()){
            clearEmptyDir(subDir);
        }
        if(dir.listFiles().length == 0){
            dir.delete();
        }
    }


}
